<template>
  <div class="app-container">
    <div v-if="isShowSearchBtn" class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="title" label="关键字">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入消息主题"
            clearable
            style="width: 350px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['notice@add']"
              type="success"
              @click="openDrawer()"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              v-hasPerm="['notice@del']"
              type="danger"
              v-if="removeIds.length > 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
            <el-button
              class="ml-3"
              @click="handleSearchShowBtn"
              icon="Search"
              circle
            />
            <el-button
              class="ml-3"
              title="刷新"
              @click="handleQuery"
              icon="Refresh"
              circle
            />
          </div>
        </div>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="NoticeList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="ID"
          align="center"
          prop="id"
          width="100"
          sortable="custom"
        />
        <el-table-column label="主题" prop="title">
          <template #default="scope">
            <el-link type="primary" :href="url + scope.row.id">
              {{ scope.row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="发布人" prop="author">
          <template #default="scope">
            {{ scope.row.author }}
          </template>
        </el-table-column>
        <el-table-column label="发送时间" prop="created_at" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['notice@edit']"
              type="success"
              circle
              @click="openDrawer(scope.row.id)"
              title="编辑"
            >
              <i-ep-edit />
            </el-button>
            <el-button
              v-hasPerm="['notice@del']"
              type="danger"
              circle
              title="删除"
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.p"
        v-model:limit="queryParams.limit"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 发送通知 -->
    <el-drawer v-model="drawer" title="发送通知" direction="rtl" size="65%">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="通知主题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入通知主题" />
        </el-form-item>

        <el-form-item label="正文" prop="content">
          <editor
            v-model="formData.content"
            style="height: calc(80vh - 180px); z-index: 999"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {
  addNotice,
  deleteNotice,
  getNoticePage,
  getNoticeForm,
} from "@/api/notice";
import { NoticeForm, NoticePage, NoticeQuery } from "@/api/notice/types";
import Editor from "@/components/WangEditor/index.vue";

defineOptions({
  name: "Notice",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const queryUserFormRef = ref(ElForm);
const url = ref("#/message/details?id=");
const formRef = ref(ElForm);
const loading = ref(false);
const total = ref(0);
const isShowSearchBtn = ref(false);
const isEdit = ref(true);
const drawer = ref(false);
const removeIds = ref([]); // 删除ID集合 用于批量删除
const selectedRows = ref([]);
const queryParams = reactive<NoticeQuery>({
  p: 1,
  limit: 10,
});
const NoticeList = ref<NoticePage[]>();
const formData = reactive<NoticeForm>({
  id: undefined,
  sort: 0,
});
const rules = reactive({
  title: [{ required: true, message: "请输入通知主题", trigger: "blur" }],
  content: [{ required: true, message: "请输入正文", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getNoticePage(queryParams)
    .then(({ data }) => {
      NoticeList.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

function openDrawer(id?: any) {
  drawer.value = drawer.value == false;
  if (id) {
    getNoticeForm(id)
      .then(({ data }) => {
        Object.assign(formData, { ...data });
      })
      .finally(() => {});
  }
}

/** 保存提交 */
function handleSubmit() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      addNotice(formData)
        .then(() => {
          resetForm();
          drawer.value = false;
          handleQuery();
          ElMessage.success("发送成功");
        })
        .finally(() => (loading.value = false));
    }
  });
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  selectedRows.value = [];
  formData.id = undefined;
  formData.title = "";
  formData.content = "";
  handleQuery();
}

/** 删除 */
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteNotice({ ids: ids })
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

/** 排序 */
function handleSortChange(data: any) {
  const { prop, order } = data;
  if (prop === "id") {
    if (order === "ascending") {
      queryParams.sort = "+id";
    } else {
      queryParams.sort = "-id";
    }
    handleQuery();
  }
}

onMounted(() => {
  handleQuery();
});
</script>

<style></style>
